import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { SearchBar, Banner, CategoryGrid, ProductCard, TabBar } from '../../components';
import api from '../../../../shared/api';
import './index.css';

// Mock轮播图数据（这部分可以保持静态）
const mockBanners = [
  {
    id: '1',
    image: 'https://via.placeholder.com/375x180/ff4757/ffffff?text=Banner+1',
    title: '轮播图1',
    link: '/mall/product/1'
  },
  {
    id: '2',
    image: 'https://via.placeholder.com/375x180/2ed573/ffffff?text=Banner+2',
    title: '轮播图2',
    link: '/mall/product/2'
  },
  {
    id: '3',
    image: 'https://via.placeholder.com/375x180/1e90ff/ffffff?text=Banner+3',
    title: '轮播图3',
    link: '/mall/product/3'
  }
];

const tabBarItems = [
  { key: 'home', title: '首页', icon: '🏠', activeIcon: '🏠', path: '/mall/' },
  { key: 'category', title: '分类', icon: '📋', activeIcon: '📋', path: '/mall/category' },
  { key: 'cart', title: '购物车', icon: '🛒', activeIcon: '🛒', path: '/mall/cart' },
  { key: 'profile', title: '我的', icon: '👤', activeIcon: '👤', path: '/mall/profile' }
];

const HomePage: React.FC = () => {
  const navigate = useNavigate();
  const [categories, setCategories] = useState<any[]>([]);
  const [hotProducts, setHotProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // 加载页面数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        
        // 并行加载分类和热门商品数据
        const [categoriesData, hotProductsData] = await Promise.all([
          api.product.getCategories(),
          api.product.getHotProducts()
        ]);
        
        setCategories(categoriesData);
        setHotProducts(hotProductsData);
        
      } catch (error) {
        console.error('加载首页数据失败:', error);
        // 如果API失败，使用默认数据
        setCategories([
          { id: '1', name: '手机数码', icon: '📱' },
          { id: '2', name: '服装鞋包', icon: '👕' },
          { id: '3', name: '家居生活', icon: '🏠' },
          { id: '4', name: '美妆护肤', icon: '💄' },
          { id: '5', name: '运动户外', icon: '⚽' },
          { id: '6', name: '食品饮料', icon: '🍎' },
          { id: '7', name: '母婴用品', icon: '🍼' },
          { id: '8', name: '图书文具', icon: '📚' }
        ]);
        
        setHotProducts([
          {
            id: '1',
            name: 'iPhone 15 Pro 钛金属材质 专业级摄影系统',
            price: 7999,
            originalPrice: 8999,
            image: 'https://via.placeholder.com/200x200/007bff/ffffff?text=iPhone+15',
            sales: 1200
          },
          {
            id: '2',
            name: '小米14 骁龙8 Gen3 徕卡光学镜头',
            price: 3999,
            originalPrice: 4299,
            image: 'https://via.placeholder.com/200x200/6f42c1/ffffff?text=小米14',
            sales: 800
          }
        ]);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  const handleSearch = (value: string) => {
    navigate(`/mall/search?keyword=${encodeURIComponent(value)}`);
  };

  const handleSearchFocus = () => {
    navigate('/mall/search');
  };

  const handleCategoryClick = (category: any) => {
    navigate(`/mall/category/${category.id}`);
  };

  const handleProductClick = (productId: string) => {
    navigate(`/mall/product/${productId}`);
  };

  if (loading) {
    return (
      <div className="home-page">
        <div className="home-page__loading">
          <div>加载中...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="home-page">
      {/* 搜索栏 */}
      <div className="home-page__search">
        <SearchBar
          placeholder="请输入商品名称"
          onSearch={handleSearch}
          onFocus={handleSearchFocus}
        />
      </div>

      {/* 轮播图 */}
      <div className="home-page__banner">
        <Banner items={mockBanners} />
      </div>

      {/* 分类网格 */}
      <div className="home-page__categories">
        <CategoryGrid
          categories={categories}
          columns={4}
          onCategoryClick={handleCategoryClick}
        />
      </div>

      {/* 品牌制造商供货 */}
      <div className="home-page__brands">
        <div className="home-page__section-title">
          <div className="home-page__title-icon">👑</div>
          <div className="home-page__title-text">品牌制造商供货</div>
          <div className="home-page__title-subtitle">工厂直供价格，制造商品质保证</div>
        </div>
        
        <div className="home-page__brand-list">
          <div className="home-page__brand-item">
            <img src="https://via.placeholder.com/80x40/ff6b35/ffffff?text=小米" alt="小米" />
            <div className="home-page__brand-info">
              <div className="home-page__brand-name">小米</div>
              <div className="home-page__brand-count">商品数量：100</div>
            </div>
          </div>
          
          <div className="home-page__brand-item">
            <img src="https://via.placeholder.com/80x40/ff4757/ffffff?text=华为" alt="华为" />
            <div className="home-page__brand-info">
              <div className="home-page__brand-name">华为</div>
              <div className="home-page__brand-count">商品数量：100</div>
            </div>
          </div>
        </div>
      </div>

      {/* 热门商品 */}
      <div className="home-page__hot-products">
        <div className="home-page__section-title">
          <div className="home-page__title-text">热门商品</div>
        </div>
        
        <div className="home-page__product-grid">
          {hotProducts.map((product) => (
            <ProductCard
              key={product.id}
              {...product}
              onProductClick={handleProductClick}
            />
          ))}
        </div>
      </div>

      {/* 底部导航 */}
      <TabBar tabs={tabBarItems} />
    </div>
  );
};

export default HomePage; 